package com.example.myFirstProject.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FileUploadAndDownloadUtils {

	private static final Logger logger = LoggerFactory.getLogger(FileUploadAndDownloadUtils.class);

	public static String upload(MultipartFile file){
		if(file.isEmpty()){
			return "文件为空";
		}
		
		String fileName= file.getOriginalFilename();
		logger.info("上传的文件名字为:"+fileName);
		String lastName= fileName.substring(fileName.lastIndexOf("."));
		logger.info("上传的文件的后缀名为:"+lastName);
		String filepath="d://test//";
		File file1= new File(filepath+lastName);
		try{		
		   file.transferTo(file1);
		   return "上传成功";
		}catch(IllegalStateException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "上传失败";
	}
	
	public static String download(HttpServletRequest request,HttpServletResponse response,String fileName,String downPath){
		if(fileName!=null){
			String realpath= request.getServletContext().getRealPath("//upanddownloader//");
			File file= new File(realpath,fileName);
			if(file.exists()){
				response.setContentType("application/force-download");
				response.addHeader("Content-Disposition","attachment;fileName="+fileName);
				byte[] byte1= new byte[1024];
				FileInputStream fileInputStream= null;
				BufferedInputStream bufferedInputStream=null;
				try{
					
					fileInputStream= new FileInputStream(file);
					bufferedInputStream= new BufferedInputStream(fileInputStream);
					OutputStream outputStream= response.getOutputStream();
					int length=0;
					while((length=bufferedInputStream.read())!=-1){
						outputStream.write(byte1);
					}
					if(length!=0){
						outputStream.close();
						logger.info("文件下载成功");
						return "文件下载成功";
					}else{
						logger.info("文件下载失败");
						return "文件下载失败";
					}	
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					try{
					  bufferedInputStream.close();
					  fileInputStream.close();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
		  }
		}
		return null;
	}


}
